﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Nextensions.WinApi;

namespace Terminal
{
    class Program
    {
        private static readonly List<string> _history = new List<string>(100);
        private static int _historyIndex = 0;
        private static int _startOfLine;

        static void Main(string[] args)
        {
            _history.AddRange(LoadHistory());

            bool prompt = true;
            StringBuilder lineBuffer = new StringBuilder(512);

            while (true)
            {
                if (prompt)
                {
                    Console.Write(">");
                    _startOfLine = 1;
                }

                ConsoleKeyInfo keyInfo = Console.ReadKey(true);

                switch (keyInfo.Key)
                {
                    case ConsoleKey.UpArrow:

                        LsHistory(-1);
                        break;

                    case ConsoleKey.DownArrow:

                        LsHistory(1);
                        break;

                    case ConsoleKey.Enter:

                        SaveHistoryItem(lineBuffer.ToString());
                        lineBuffer.Clear();
                        Console.WriteLine();
                        break;

                    default:

                        lineBuffer.Append(keyInfo.KeyChar);
                        Console.Write(keyInfo.KeyChar);
                        break;
                }

                prompt = keyInfo.Key == ConsoleKey.Enter;

                //CommandPipe pipe = new CommandPipe();
                //Console.Write(pipe.Execute());
            }
        }

        private static void GoToStartOfLine()
        {
            Console.CursorLeft = _startOfLine;
        }

        private static void ClearLine()
        {
        }

        private static void LsHistory(int step)
        {
            int index = _historyIndex + step;
            if (index < 0 || index >= _history.Count)
                return;

            GoToStartOfLine();
            ClearLine();
            Console.Write(_history[_historyIndex = index]);
        }

        private static string[] LoadHistory()
        {
            if(!File.Exists(HistoryFile))
                return new string[0];

            string[] history;

            try
            {
                return File.ReadAllLines(HistoryFile);
            }
            catch
            {
                return new string[0];
            }
        }

        private static string HistoryFile
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "cmd2.hs");
            }
        }
    }
}
